#include "checkout.h"
#include "ui_checkout.h"

#include "personmember.h"
#include "inquiresql.h"
#include "staffresultclass.h"
#include "saleorderform.h"

#include <QDateTime>
#include <QMessageBox>
#include <QKeyEvent>
#include <QDebug>
#include <QRegExpValidator>

Checkout::Checkout(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Checkout)
{
    ui->setupUi(this);
    this->setLayout(ui->MainLayout);
    this->setFixedSize(375, 443);
    setWindowTitle(tr("结帐"));

    //设置自定义的鼠标指针图案
    QCursor *myCursor= new QCursor(QPixmap(":/Mouse/Image/mouse/mouse.png"),15,10);
    setCursor(*myCursor);

    m_lastClick = -1;
    ui->lineEditRealPayment->setDisabled(true);

    QRegExp regExpPrice(" [0-9]{0,6}|[0-9]{0,6}[.]{1}[0-9]{0,2} ");
    QRegExpValidator *pRegExpValidatorPrice = new QRegExpValidator(regExpPrice, this);
    ui->lineEditCashPays->setValidator(pRegExpValidatorPrice);
    ui->lineEditCUPPays->setValidator(pRegExpValidatorPrice);
    ui->lineEditMemberPays->setValidator(pRegExpValidatorPrice);
    ui->lineEditRealPayment->setValidator(pRegExpValidatorPrice);

    //消除边框
    ui->pushButtonF1MemberPays->setFlat(true);
    ui->pushButtonF2CashPays->setFlat(true);
    ui->pushButtonF3CUPPays->setFlat(true);
    ui->pushButtonCheckout->setFlat(true);
    ui->pushButtonCancel->setFlat(true);

    //添加时间过滤器
    ui->lineEditRealPayment->installEventFilter(this);
    ui->lineEditMemberPays->installEventFilter(this);
    ui->lineEditCashPays->installEventFilter(this);
    ui->lineEditCUPPays->installEventFilter(this);
    ui->pushButtonCheckout->installEventFilter(this);
}

Checkout::~Checkout()
{
    delete ui;
}

void Checkout::displayMemberInformation(const PersonMember &memberInformation)
{
    ui->labelMemberCardNumber->setText(memberInformation.get_personID());
    ui->labelMemberName->setText(memberInformation.get_personName());
    ui->labelMemberCardOver->setText(memberInformation.get_membercardAmount());
    ui->labelMemberIntegration->setText(memberInformation.get_integration());
}

void Checkout::set_amountsReceivable(const QString &amountsReceivable)
{
    ui->labelAmountsReceivable->setText(amountsReceivable);
    ui->lineEditRealPayment->setText(amountsReceivable);
//    ui->lineEditRealPayment->setFocus();
//    ui->lineEditRealPayment->selectAll();
    m_amountsReceivable = amountsReceivable;

    if (ui->labelMemberCardNumber->text() == tr("非会员"))
    {
        ui->lineEditMemberPays->setDisabled(true);
        ui->pushButtonF1MemberPays->setDisabled(true);
        m_isMember = false;
        m_payMode = cashPay;
        ui->lineEditMemberPays->setText("0.00");
        ui->lineEditCUPPays->setText("0.00");
        ui->lineEditCashPays->setText(amountsReceivable);
        ui->lineEditCashPays->setFocus();
    }
    else
    {
        ui->lineEditMemberPays->setDisabled(false);
        ui->pushButtonF1MemberPays->setDisabled(false);
        m_isMember = true;
        m_payMode = memberPay;
        ui->lineEditCashPays->setText("0.00");
        ui->lineEditCUPPays->setText("0.00");
        ui->lineEditMemberPays->setText(amountsReceivable);
        ui->lineEditMemberPays->setFocus();
    }
    ui->lineEditRealPayment->setText(amountsReceivable);
}

bool Checkout::eventFilter(QObject *target, QEvent *event)
{
    if (target == ui->lineEditRealPayment || target == ui->lineEditMemberPays
     || target == ui->lineEditCashPays || target == ui->lineEditCUPPays
     || target == ui->pushButtonCheckout)
    {
        if (event->type() == QEvent::FocusOut)
        {
            if (target == ui->lineEditCashPays)
            {
                switch (m_payMode)
                {
                    case cashPay:
                    {
                        ui->lineEditMemberPays->setText("0.00");
                        ui->lineEditCUPPays->setText("0.00");
                        if (ui->lineEditCashPays->text().toDouble()
                        < ui->labelAmountsReceivable->text().toDouble())
                            ui->lineEditCashPays->setText(ui->labelAmountsReceivable->text());
                        else
                        {
                            ui->labelKeepTheChange->setText(QString::number(
                                ui->lineEditCashPays->text().toDouble()
                              - ui->labelAmountsReceivable->text().toDouble(), 'd', 2));
                        }
                        break;
                    }
                    case memberPay:
                    {
                        if (ui->lineEditMemberPays->text().toDouble()
                                == ui->labelAmountsReceivable->text().toDouble())
                            ui->lineEditCashPays->setText("0.00");
//                        else
//                        {
//                            ui->lineEditCashPays->setText(QString::number(
//                                    ui->labelAmountsReceivable->text().toDouble()
//                                  - ui->lineEditMemberPays->text().toDouble(), 'd', 2));
//                        }
                        ui->lineEditCUPPays->setText("0.00");
                        break;
                    }
                    case CUPPay:
                    {
                        if (ui->lineEditCUPPays->text().toDouble()
                                == ui->labelAmountsReceivable->text().toDouble())
                            ui->lineEditCashPays->setText("0.00");
//                        else
//                        {
//                            ui->lineEditCashPays->setText(QString::number(
//                                    ui->labelAmountsReceivable->text().toDouble()
//                                  - ui->lineEditCUPPays->text().toDouble(), 'd', 2));
//                        }
                        ui->lineEditMemberPays->setText("0.00");
                        break;
                    }
                }
            }
            if (target == ui->lineEditMemberPays)
            {
                switch (m_payMode)
                {
                    case CUPPay:
                    case cashPay:
                    {
                        ui->lineEditMemberPays->setText("0.00");
                        break;
                    }
                    case memberPay:
                    {
                        if (ui->lineEditMemberPays->text().toDouble()
                                == ui->labelAmountsReceivable->text().toDouble())
                            ui->lineEditCashPays->setText("0.00");
                        else
                        {
//                            qDebug() << "into";
                            ui->lineEditCashPays->setText(QString::number(
                                    ui->labelAmountsReceivable->text().toDouble()
                                  - ui->lineEditMemberPays->text().toDouble(), 'd', 2));
                        }
                        break;
                    }
                }
                if (ui->lineEditMemberPays->text().toDouble()
                        > ui->labelMemberCardOver->text().toDouble())
                {
                    ui->lineEditMemberPays->setText(ui->labelMemberCardOver->text());
                }
            }
            if (target == ui->lineEditCUPPays)
            {
                switch (m_payMode)
                {
                    case memberPay:
                        break;
                    case cashPay:
                    {
                        ui->lineEditMemberPays->setText("0.00");
                        break;
                    }
                    case CUPPay:
                    {
                        if (ui->lineEditCUPPays->text().toDouble()
                                == ui->labelAmountsReceivable->text().toDouble())
                            ui->lineEditCashPays->setText("0.00");
                        else
                        {
                            ui->lineEditCashPays->setText(QString::number(
                                    ui->labelAmountsReceivable->text().toDouble()
                                  - ui->lineEditCUPPays->text().toDouble(), 'd', 2));
                        }
                        break;
                    }
                }
            }
        }
        //鼠标左键按下事件
        if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            if (mouseEvent->button() == Qt::LeftButton)
            {
                if (target == ui->lineEditRealPayment)
                {
                    m_lastClick = lineEditRealPayment;
                    return true;
                }
                if (target == ui->lineEditMemberPays)
                {
                    if (m_lastClick != lineEditMemberPays){
                        m_lastClick = lineEditMemberPays;
                        if (m_isMember)
                            ui->lineEditMemberPays->selectAll();
                        return true;
                    }else if (m_lastClick == lineEditMemberPays)
                    {
                        goto flag;
                    }
                }
                if (target == ui->lineEditCashPays)
                {
                    if (m_lastClick != lineEditCashPays){
                        m_lastClick = lineEditCashPays;
                        ui->lineEditCashPays->selectAll();
                        return true;
                    }else if (m_lastClick == lineEditCashPays)
                    {
                        goto flag;
                    }
                }
                if (target == ui->lineEditCUPPays)
                {
                    if (m_lastClick != lineEditCUPPays){
                        m_lastClick = lineEditCUPPays;
                        ui->lineEditCUPPays->selectAll();
                        return true;
                    }else if (m_lastClick == lineEditCUPPays)
                    {
                        goto flag;
                    }
                }
            }
        }

        //键盘事件
        if (event->type() == QEvent::KeyPress)
        {
            QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
            if (keyEvent->key() == Qt::Key_Escape)
            {
                this->hide();
                return true;
            }
            if ((keyEvent->key() == Qt::Key_Enter) || (keyEvent->key() == Qt::Key_Return))
            {
                if (target == ui->lineEditRealPayment)
                {
                    if (!m_isMember)
                    {
                        ui->lineEditMemberPays->setFocus();
                        ui->lineEditMemberPays->selectAll();
                    }
                    else
                    {
                        ui->lineEditCashPays->setFocus();
                        ui->lineEditCashPays->selectAll();
                    }
                    return true;
                }
                if (target == ui->lineEditMemberPays)
                {
                    ui->lineEditCashPays->setFocus();
                    ui->lineEditCashPays->selectAll();
                    return true;
                }
                if (target == ui->lineEditCashPays)
                {
                    ui->lineEditCUPPays->setFocus();
                    ui->lineEditCUPPays->selectAll();
                    return true;
                }
                if (target == ui->lineEditCUPPays)
                {
                    ui->pushButtonCheckout->setFocus();
                    return true;
                }
                if (target == ui->pushButtonCheckout)
                {
                    on_pushButtonCheckout_clicked();
                }
            }
        }
    }
flag:
    return QWidget::eventFilter(target, event);
}

void Checkout::on_pushButtonCancel_clicked()
{
    this->hide();
}

void Checkout::on_pushButtonF1MemberPays_clicked()
{
    m_payMode = memberPay;
    ui->lineEditMemberPays->setText(m_amountsReceivable);
    ui->lineEditMemberPays->setFocus();
    ui->lineEditMemberPays->selectAll();
    ui->lineEditCashPays->setText("0.00");
    ui->lineEditCUPPays->setText("0.00");
    ui->lineEditRealPayment->setText(m_amountsReceivable);
}

void Checkout::on_pushButtonF2CashPays_clicked()
{
    m_payMode = cashPay;
    ui->lineEditCashPays->setText(m_amountsReceivable);
    ui->lineEditCashPays->setFocus();
    ui->lineEditCashPays->selectAll();
    ui->lineEditMemberPays->setText("0.00");
    ui->lineEditCUPPays->setText("0.00");
    ui->lineEditRealPayment->setText(m_amountsReceivable);
}

void Checkout::on_pushButtonF3CUPPays_clicked()
{
    m_payMode = CUPPay;
    ui->lineEditCUPPays->setText(m_amountsReceivable);
    ui->lineEditCUPPays->setFocus();
    ui->lineEditCUPPays->selectAll();
    ui->lineEditMemberPays->setText("0.00");
    ui->lineEditCashPays->setText("0.00");
    ui->lineEditRealPayment->setText(m_amountsReceivable);
}

void Checkout::on_lineEditRealPayment_editingFinished()
{
    if (ui->lineEditRealPayment->text().toDouble() <
        ui->labelAmountsReceivable->text().toDouble())
    {
        QMessageBox::warning(this, tr("(☆_☆)温馨提示 ..."),
                             tr("\n支付金额不足,请重新添加实收金额!"));
        ui->lineEditRealPayment->setFocus();
        ui->lineEditRealPayment->setText("0.00");
        ui->lineEditRealPayment->selectAll();
        return;
    }
    switch (m_payMode)
    {
        case cashPay:
            ui->lineEditCashPays->setText(ui->labelAmountsReceivable->text());
            ui->lineEditCashPays->setFocus();
            ui->lineEditCashPays->setFocus();
            break;
        case memberPay:
            ui->lineEditMemberPays->setText(ui->labelAmountsReceivable->text());
            ui->lineEditMemberPays->setFocus();
            ui->lineEditMemberPays->setFocus();
            break;
        case CUPPay:
            ui->lineEditCUPPays->setText(ui->labelAmountsReceivable->text());
            ui->lineEditCUPPays->setFocus();
            ui->lineEditCUPPays->setFocus();
            break;
        default:
            qDebug() << "error1";
            break;
    }
}

void Checkout::on_pushButtonCheckout_clicked()
{       
    switch(QMessageBox::question(this, tr("(☆_☆)温馨提示 ..."),
                             tr(" \n您确认要结帐吗? "
                                " \n-------------- "
                                " \n应收金额:%1 "
                                " \n实收金额:%2\n "
                                " \n会员支付:%3 "
                                " \n现金支付:%4 "
                                " \n银联支付:%5\n "
                                " \n找零金额:%6 "
                                " \n-------------- "
                                " \n以上信息确认无误? ")
                             .arg(ui->labelAmountsReceivable->text(),
                                  ui->lineEditRealPayment->text(),
                                  ui->lineEditMemberPays->text(),
                                  ui->lineEditCashPays->text(),
                                  ui->lineEditCUPPays->text(),
                                  ui->labelKeepTheChange->text()),
                                 QMessageBox::Yes | QMessageBox::No,
                                 QMessageBox::Yes))
    {
        case QMessageBox::Yes:
        {
//        qDebug() << "hello";
//        qDebug() << m_staffID;
//        SaleOrderForm(const QString saleOrderFormNumber, const QString memberCardNumber,
//                      const QString memberName, const QString quantity,
//                      const QString totalSales, const QString integration,
//                      const QString memberPayment, const QString cashPayment,
//                      const QString CUPPayment, const QString staffName,
//                      const QString salesDate)
            QString memberCardNumber, memberName;
            if (ui->labelMemberCardNumber->text() == tr("非会员"))
                memberCardNumber = "";
            else
                memberCardNumber = ui->labelMemberCardNumber->text();
            if (ui->labelMemberName->text() == tr("非会员"))
                memberName = "";
            else
                memberName = ui->labelMemberName->text();

            SaleOrderForm saleOrderForm(m_salesOrderFormNumber,
                                        memberCardNumber,
                                        memberName,
                                        m_quantity,
                                        ui->labelAmountsReceivable->text(),
                                        m_integration,
                                        ui->lineEditMemberPays->text(),
                                        ui->lineEditCashPays->text(),
                                        ui->lineEditCUPPays->text(),
                                        m_staffID,
                                        QDateTime::currentDateTime().toString("yyyy-MM-dd"));

            if (!m_sql->InsertSalesOrderForm(saleOrderForm))
            {
                QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("插入销售单据失败") );
                return;
            }
            if (!m_sql->InsertSalesDetail(m_salesOrderFormNumber ,m_saleDetailList))
            {
                QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("插入销售明细失败") );
                return;
            }
            else
            {
//                QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("交易完成") );
                emit signalInit();
            }
            if ( !(ui->labelMemberCardNumber->text() == tr("非会员")) )
            {
                m_personMember = m_sql->InquireMemberInformation(
                            ui->labelMemberCardNumber->text());

                m_personMember.set_integration(QString::number(m_integration.toInt()
                                        + m_personMember.get_integration().toInt()));

                m_personMember.set_membercardAmount(
                            QString::number(ui->labelMemberCardOver->text().toDouble()
                            - ui->lineEditMemberPays->text().toDouble(), 'd', 2));

                m_personMember.set_totalSpending(
                            QString::number(ui->labelAmountsReceivable->text().toDouble()
                                + m_personMember.get_totalSpending().toDouble(), 'd', 2));
                m_personMember.set_consumeTimes(QString::number(m_personMember.get_consumeTimes().toInt() + 1));
                if (!m_sql->UpdatMemberOver(m_personMember))
                {
                    QMessageBox::warning(this, tr("(☆_☆)温馨提示 ..."),
                                         tr("\n更新会员信息失败!"));
                    return;
                }
            }

            StaffResultClass staffResultClass(m_staffID, "", "", m_quantity,
                ui->labelAmountsReceivable->text(), m_cost,
                QString::number(ui->labelAmountsReceivable->text().toDouble()
                - m_cost.toDouble()), "");
            if (!m_sql->UpdatStaffSalesResult(staffResultClass))
            {
                QMessageBox::warning(this, tr("(☆_☆)温馨提示 ..."),
                                     tr("\n更新员工销售业绩失败!"));
            }

            //交易成功提示
            QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."),
                                 tr("\n结算成功, 谢谢您的惠顾!"));
            this->hide();
        }
            break;
        case QMessageBox::No:
            qDebug() << "No";
            break;
        default:
            break;
    }
}

void Checkout::on_lineEditRealPayment_textChanged(const QString &realPayment)
{
    ui->labelKeepTheChange->setText(QString::number(
        realPayment.toDouble()
      - ui->lineEditMemberPays->text().toDouble()
      - ui->lineEditCashPays->text().toDouble()
      - ui->lineEditCUPPays->text().toDouble(), 'd', 2));
}

void Checkout::on_lineEditCashPays_textChanged(const QString &cashPays)
{
    switch (m_payMode)
    {
        case cashPay:
        {
            ui->lineEditRealPayment->setText(cashPays);
            if (cashPays.toDouble() > ui->labelAmountsReceivable->text().toDouble())
                ui->labelKeepTheChange->setText(QString::number(
                    ui->lineEditCashPays->text().toDouble()
                  - ui->labelAmountsReceivable->text().toDouble(), 'd', 2));
            else
            {
                ui->labelKeepTheChange->setText("0.00");
            }
            break;
        }
        case memberPay:
        {
            if (ui->lineEditMemberPays->text().toDouble()
                    == ui->labelAmountsReceivable->text().toDouble())
            {
//                qDebug() << "into2";
                ui->lineEditCashPays->setText("0.00");
                break;
            }
            if (ui->lineEditCashPays->text().isEmpty())
            {
                ui->lineEditRealPayment->setText(ui->lineEditMemberPays->text());
                ui->lineEditCashPays->setText("0.00");
                break;
            }
            else
            {
                ui->lineEditRealPayment->setText(QString::number(
                cashPays.toDouble() + ui->lineEditMemberPays->text().toDouble(), 'd', 2));
            }
            if (cashPays.toDouble() + ui->lineEditMemberPays->text().toDouble()
                    > ui->labelAmountsReceivable->text().toDouble() )
            {
//                ui->lineEditRealPayment->setText(QString::number(
//                cashPays.toDouble() + ui->lineEditMemberPays->text().toDouble(), 'd', 2));
                ui->labelKeepTheChange->setText(QString::number(
                    ui->lineEditRealPayment->text().toDouble()
                  - ui->labelAmountsReceivable->text().toDouble(), 'd', 2));
            }
            break;
        }
        case CUPPay:
        {
            if (ui->lineEditCUPPays->text().toDouble()
                    == ui->labelAmountsReceivable->text().toDouble())
            {
                ui->lineEditCashPays->setText("0.00");
                break;
            }
            if (ui->lineEditCashPays->text().isEmpty())
            {
                ui->lineEditRealPayment->setText(ui->lineEditCUPPays->text());
//                ui->lineEditCashPays->setText("0.00");
                break;
            }
            else
            {
                ui->lineEditRealPayment->setText(QString::number(
                cashPays.toDouble() + ui->lineEditCUPPays->text().toDouble(), 'd', 2));
            }
            if (cashPays.toDouble() + ui->lineEditCUPPays->text().toDouble()
                    > ui->labelAmountsReceivable->text().toDouble() )
            {
//                ui->lineEditRealPayment->setText(QString::number(
//                cashPays.toDouble() + ui->lineEditCUPPays->text().toDouble(), 'd', 2));
                ui->labelKeepTheChange->setText(QString::number(
                    ui->lineEditRealPayment->text().toDouble()
                  - ui->labelAmountsReceivable->text().toDouble(), 'd', 2));
            }
            break;
        }
        default:
            qDebug() << "error2";
            break;
    }
}

void Checkout::on_lineEditMemberPays_textChanged(const QString &)
{
    switch (m_payMode)
    {
        case cashPay:
        case CUPPay:
        {
            ui->lineEditMemberPays->setText("0.00");
            break;
        }
        case memberPay:
        {
            if (ui->lineEditMemberPays->text().toDouble()
                    > ui->labelAmountsReceivable->text().toDouble())
                ui->lineEditMemberPays->setText(ui->labelAmountsReceivable->text());
            else
            {
                ui->lineEditCashPays->setText(QString::number(
                            ui->labelAmountsReceivable->text().toDouble()
                          - ui->lineEditMemberPays->text().toDouble(), 'd', 2));
            }
            break;
        }
        default:
        {
            qDebug() << "error3";
            break;
        }
    }
}

void Checkout::on_lineEditCUPPays_textChanged(const QString &)
{
    switch (m_payMode)
    {
        case cashPay:
        case memberPay:
        {
            ui->lineEditCUPPays->setText("0.00");
            break;
        }
        case CUPPay:
        {
            if (ui->lineEditCUPPays->text().toDouble()
                    > ui->labelAmountsReceivable->text().toDouble())
                ui->lineEditCUPPays->setText(ui->labelAmountsReceivable->text());
            else
            {
                ui->lineEditCashPays->setText(QString::number(
                            ui->labelAmountsReceivable->text().toDouble()
                          - ui->lineEditCUPPays->text().toDouble(), 'd', 2));
            }
            break;
        }
        default:
            qDebug() << "error4";
            break;
    }
}
